package com.cy.aircompressor.main.ui.Infoover.fragment;

import android.os.Bundle;
import android.text.TextUtils;

import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.cy.aircompressor.config.AirConfig;
import com.cy.aircompressor.databinding.ChildInfooverFragmentBinding;
import com.cy.aircompressor.entity.compressor.Compressor;
import com.cy.aircompressor.entity.maintenance.MaintenanceRecord;
import com.cy.aircompressor.entity.sensor.Sensor;
import com.cy.aircompressor.entity.sensor.SensorLatestData;
import com.cy.aircompressor.entity.warning.WarningMsg;
import com.cy.aircompressor.main.ui.Infoover.provider.CompressorItemProvider;
import com.cy.aircompressor.main.home.fragment.provider.MaintenanceRecordProvider;
import com.cy.aircompressor.main.home.fragment.provider.WarningMsgProvider;
import com.cy.aircompressor.main.ui.Infoover.viewmodel.InformationOverviewViewModel;
import com.cy.aircompressor.main.home.other.WarningFragment;
import com.cy.aircompressor.main.view.spaceItem.GridSpaceItemDecoration;
import com.drug.lib.util.DensityUtil;
import com.drug.lib.view.recycptr.DynamicAdpTypePool;
import com.drug.lib.view.recycptr.DynamicRecyclerAdapter;
import com.drug.lib.view.recycptr.bean.RowEntity;
import com.jakewharton.rxbinding2.view.RxView;
import com.net.model.base.Resource;
import com.net.model.base.fragment.BaseVMFragment;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.stream.Collectors;


/**
 * Created by YoKeyword on 16/6/3.
 * 信息总览
 */
public class InformationOverviewFragment extends BaseVMFragment<ChildInfooverFragmentBinding, InformationOverviewViewModel> {
    DynamicRecyclerAdapter airCompressorAdapter;
    DynamicRecyclerAdapter warningMsgAdapter;
    DynamicRecyclerAdapter maintenanceRecordAdapter;

    public static InformationOverviewFragment newInstance() {
        Bundle args = new Bundle();
        InformationOverviewFragment fragment = new InformationOverviewFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected ChildInfooverFragmentBinding getViewBinding() {
        return ChildInfooverFragmentBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        initAirCompressorRecycler();
        initWarningMsgRecycler();
        initMaintenanceRecordRecycler();
        RxView.clicks(mBinding.btnMore)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    WarningFragment.showDialogFragment(getChildFragmentManager(), "3", null);
                });
    }

    @Override
    protected void requestNetwork() {
        if (AirConfig.get().userInfo != null) {
            mViewModel.compressor(1, AirConfig.get().userInfo.getPowerStationId(), null);
            mViewModel.queryMaintenanceRecordByPage(1, null, AirConfig.get().userInfo.getPowerStationId());
            mViewModel.querySensorByPage(AirConfig.get().userInfo.getPowerStationId());
        }
        mViewModel.queryWarningByPage();
    }


    @Override
    protected void dataChange() {
        mViewModel.getCompressorObservable().observe(this, new Observer<Resource<RowEntity<Compressor>>>() {
            @Override
            public void onChanged(Resource<RowEntity<Compressor>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<RowEntity<Compressor>>() {
                    @Override
                    public void onSuccess(RowEntity<Compressor> data) {
                        airCompressorAdapter.setItems(data.getList());
                        airCompressorAdapter.notifyDataSetChanged();
                        mBinding.airNum.setText(String.valueOf(data.getTotal()));
                        queryCompressorSensor(data.getList());
                    }
                });
            }
        });

        mViewModel.getQueryCompressorSensorDataObservable().observe(this, new Observer<Resource<List<SensorLatestData>>>() {
            @Override
            public void onChanged(Resource<List<SensorLatestData>> sensorDataResource) {
                sensorDataResource.handler(new OnCallback<List<SensorLatestData>>() {
                    @Override
                    public void onSuccess(List<SensorLatestData> data) {
                        if (data == null) return;
                        List<Compressor> compressors = airCompressorAdapter.getItems();
                        for (int i = 0; i < compressors.size(); i++) {
                            Compressor compressor = compressors.get(i);
                            SensorLatestData sensorLatestData = getSensorRealTimeData(compressor, data);
                            compressor.setSensorLatestData(sensorLatestData);

                        }
                        airCompressorAdapter.notifyDataSetChanged();

                    }
                });
            }
        });
        mViewModel.getQueryWarningByPageObservable().observe(this, new Observer<Resource<RowEntity<WarningMsg>>>() {
            @Override
            public void onChanged(Resource<RowEntity<WarningMsg>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<RowEntity<WarningMsg>>() {
                    @Override
                    public void onSuccess(RowEntity<WarningMsg> data) {
                        warningMsgAdapter.setItems(data.getList());
                        warningMsgAdapter.notifyDataSetChanged();
                        mBinding.warningNum.setText(String.valueOf(data.getTotal()));
                    }
                });
            }
        });

        mViewModel.getQueryMaintenanceRecordByPageObservable().observe(this, new Observer<Resource<RowEntity<MaintenanceRecord>>>() {
            @Override
            public void onChanged(Resource<RowEntity<MaintenanceRecord>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<RowEntity<MaintenanceRecord>>() {
                    @Override
                    public void onSuccess(RowEntity<MaintenanceRecord> data) {
                        maintenanceRecordAdapter.setItems(data.getList());
                        maintenanceRecordAdapter.notifyDataSetChanged();
                    }
                });
            }
        });

        mViewModel.getQuerySensorByPage().observe(this, new Observer<Resource<RowEntity<Sensor>>>() {
            @Override
            public void onChanged(Resource<RowEntity<Sensor>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<RowEntity<Sensor>>() {
                    @Override
                    public void onSuccess(RowEntity<Sensor> data) {
                        mBinding.sensorNum.setText(String.valueOf(data.getTotal()));
                    }
                });
            }
        });
    }

    private SensorLatestData getSensorRealTimeData(Compressor compressor, List<SensorLatestData> data) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            List<SensorLatestData> sensorLatestDataList = data.stream()
                    .filter(new Predicate<SensorLatestData>() {
                        @Override
                        public boolean test(SensorLatestData sensorRealTimeData) {
                            return TextUtils.equals(sensorRealTimeData.getCompressorId(), compressor.getId());
                        }
                    }).collect(Collectors.toList());
            if (sensorLatestDataList != null && sensorLatestDataList.size() > 0) {
                return sensorLatestDataList.get(0);
            }
        }
        return null;
    }

    private void queryCompressorSensor(List<Compressor> compressors) {
        List<String> list = new ArrayList<>();
        int running = 0;
        int stoping = 0;
        if (compressors != null) {
            for (Compressor compressor : compressors) {
                list.add(compressor.getId());
                if (compressor.getRunningState() == 1) {
                    running++;
                } else {
                    stoping++;
                }
            }
        }
        mBinding.airRunning.setText(String.valueOf(running));
        mBinding.airStoping.setText(String.valueOf(stoping));
        mViewModel.queryCompressorSensorData(list);
    }


    private void initAirCompressorRecycler() {
        GridLayoutManager mLayoutManager = new GridLayoutManager(mContext, 2);
        // 添加间距
        mBinding.recyclerView.addItemDecoration(new GridSpaceItemDecoration(2,
                DensityUtil.dip2px(10),
                DensityUtil.dip2px(10)));
        mBinding.recyclerView.setLayoutManager(mLayoutManager);
        airCompressorAdapter = new DynamicRecyclerAdapter();
        DynamicAdpTypePool pool = new DynamicAdpTypePool();
        CompressorItemProvider compressorItemProvider = new CompressorItemProvider(mContext);
        pool.register(Compressor.class, compressorItemProvider);
        airCompressorAdapter.registerAll(pool);
        mBinding.recyclerView.setAdapter(airCompressorAdapter);
    }

    private void initWarningMsgRecycler() {
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext);
        mBinding.warningRecyc.setLayoutManager(mLayoutManager);
        warningMsgAdapter = new DynamicRecyclerAdapter();
        DynamicAdpTypePool pool = new DynamicAdpTypePool();
        WarningMsgProvider warningMsgProvider = new WarningMsgProvider();
        pool.register(WarningMsg.class, warningMsgProvider);
        warningMsgAdapter.registerAll(pool);
        mBinding.warningRecyc.setAdapter(warningMsgAdapter);
    }

    private void initMaintenanceRecordRecycler() {
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext);
        mBinding.maintenanceRecordRecyc.setLayoutManager(mLayoutManager);
        maintenanceRecordAdapter = new DynamicRecyclerAdapter();
        DynamicAdpTypePool pool = new DynamicAdpTypePool();
        MaintenanceRecordProvider maintenanceRecordProvider = new MaintenanceRecordProvider();
        pool.register(MaintenanceRecord.class, maintenanceRecordProvider);
        maintenanceRecordAdapter.registerAll(pool);
        mBinding.maintenanceRecordRecyc.setAdapter(maintenanceRecordAdapter);
    }
}
